package com.css.zfzx.fxpg.modules.percent.casualty.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.modules.casulaty.probability.repository.entity.FxCasulatyProbabilityEntity;
import com.css.zfzx.fxpg.modules.percent.casualty.repository.FxCasualtyPercentNativeRepository;
import com.css.zfzx.fxpg.modules.percent.casualty.repository.FxCasualtyPercentRepository;
import com.css.zfzx.fxpg.modules.percent.casualty.repository.entity.FxCasualtyPercentEntity;
import com.css.zfzx.fxpg.modules.percent.casualty.service.FxCasualtyPercentService;
import com.css.zfzx.fxpg.modules.percent.casualty.viewobjects.FxCasualtyPercentQueryParams;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.fxpg.modules.percent.casualty.viewobjects.FxCasualtyPercentVO;
import com.css.zfzx.fxpg.modules.percent.daynight.repository.entity.FxDayNightPercentEntity;
import com.css.zfzx.fxpg.modules.percent.daynight.viewobjects.FxDayNightPercentVO;
import com.css.zfzx.fxpg.modules.workarea.repository.entity.FxWorkareaEntity;
import com.css.zfzx.fxpg.modules.workarea.viewobjects.FxWorkareaQueryParams;
import com.css.zfzx.fxpg.modules.workarea.viewobjects.FxWorkareaVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author leon
 * @date 2020-11-13
 */
@Service
@Slf4j
public class FxCasualtyPercentServiceImpl implements FxCasualtyPercentService {

    @Autowired
    private FxCasualtyPercentRepository fxCasualtyPercentRepository;
    @Autowired
    private FxCasualtyPercentNativeRepository fxCasualtyPercentNativeRepository;

    @Override
    public JSONObject queryFxCasualtyPercents(FxCasualtyPercentQueryParams queryParams, int curPage, int pageSize) {
        Page<FxCasualtyPercentEntity> fxCasualtyPercentPage = this.fxCasualtyPercentNativeRepository.queryFxCasualtyPercents(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxCasualtyPercentPage);
        return jsonObject;
    }


    @Override
    public FxCasualtyPercentEntity getFxCasualtyPercent(String id) {
        FxCasualtyPercentEntity fxCasualtyPercent = this.fxCasualtyPercentRepository.findById(id).orElse(null);
        return fxCasualtyPercent;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxCasualtyPercentEntity saveFxCasualtyPercent(FxCasualtyPercentEntity fxCasualtyPercent) {
        String uuid = UUIDGenerator.getUUID();
        fxCasualtyPercent.setId(uuid);
        fxCasualtyPercent.setCreateUser(PlatformSessionUtils.getUserId());
        fxCasualtyPercent.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxCasualtyPercentRepository.save(fxCasualtyPercent);
        return fxCasualtyPercent;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxCasualtyPercentEntity updateFxCasualtyPercent(FxCasualtyPercentEntity fxCasualtyPercent) {
        fxCasualtyPercent.setUpdateUser(PlatformSessionUtils.getUserId());
        fxCasualtyPercent.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxCasualtyPercent.getId();
        FxCasualtyPercentEntity one = fxCasualtyPercentRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxCasualtyPercent, one);
        this.fxCasualtyPercentRepository.save(one);
        return fxCasualtyPercent;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxCasualtyPercents(List<String> ids) {
        List<FxCasualtyPercentEntity> fxCasualtyPercentList = this.fxCasualtyPercentRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(fxCasualtyPercentList) && fxCasualtyPercentList.size() > 0) {
            for (FxCasualtyPercentEntity fxCasualtyPercent : fxCasualtyPercentList) {
                this.fxCasualtyPercentRepository.delete(fxCasualtyPercent);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public List<FxCasualtyPercentEntity> listFxCasualtyPercents(FxCasualtyPercentQueryParams queryParams) {
        return fxCasualtyPercentNativeRepository.listFxCasualtyPercents(queryParams);
    }

    @Override
    public void initialize() {
        List<FxCasualtyPercentEntity> all = fxCasualtyPercentRepository.findAll();
        if (all != null && all.size() > 0) {
            throw new RuntimeException("请删除所有数据后进行初始化！");
        } else {
            List<DivisionEntity> provinceDivisions = PlatformAPI.getDivisionAPI().getSubDivisions("root");
            for (DivisionEntity provinceDivision : provinceDivisions) {
                // 省
                String province = provinceDivision.getDivisionName();
                // 直辖市
                if ("北京市".equals(province) || "天津市".equals(province) || "上海市".equals(province) || "重庆市".equals(province)) {
                    // 市
                    String city = province;
                    List<DivisionEntity> areaDivisions = PlatformAPI.getDivisionAPI().getSubDivisions(provinceDivision.getDivisionId());
                    for (DivisionEntity areaDivision : areaDivisions) {
                        FxCasualtyPercentEntity entity = new FxCasualtyPercentEntity();
                        // 区
                        String area = areaDivision.getDivisionName();
                        entity.setProvince(province);
                        entity.setCity(city);
                        entity.setArea(area);
                        // 类型字典值并且保存
                        saveInitialize(entity);
                    }
                    // 临时只添加一个直辖市
                    break;
                }
                // 省下面的正常市
                else {
                    List<DivisionEntity> cityDivisions = PlatformAPI.getDivisionAPI().getSubDivisions(provinceDivision.getDivisionId());
                    for (DivisionEntity cityDivision : cityDivisions) {
                        // 市
                        String city = cityDivision.getDivisionName();
                        List<DivisionEntity> areaDivisions = PlatformAPI.getDivisionAPI().getSubDivisions(cityDivision.getDivisionId());
                        for (DivisionEntity areaDivision : areaDivisions) {
                            // 区
                            String area = areaDivision.getDivisionName();
                            FxCasualtyPercentEntity entity = new FxCasualtyPercentEntity();
                            entity.setProvince(province);
                            entity.setCity(city);
                            entity.setArea(area);
                            // 类型字典值并且保存
                            saveInitialize(entity);
                        }
                    }
                }
                // 临时添加数据，只添加北京的；正式时候去掉break
                break;
            }
        }
    }

    @Override
    public String exportExcel(FxCasualtyPercentQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxCasualtyPercentEntity> entities = fxCasualtyPercentNativeRepository.listFxCasualtyPercents(queryParams);
            // 深拷贝
            ArrayList<FxCasualtyPercentVO> vos = new ArrayList<>();
            for (FxCasualtyPercentEntity entity : entities) {
                FxCasualtyPercentVO vo = new FxCasualtyPercentVO();
                BeanUtils.copyProperties(entity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "人员伤亡率", "人员伤亡率", FxCasualtyPercentVO.class, "人员伤亡率.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            params.setTitleRows(1);
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxCasualtyPercentVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxCasualtyPercentVO.class, params);
            List<FxCasualtyPercentVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxCasualtyPercentVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxCasualtyPercentVO vo = iterator.next();
                    String error = "";
                    returnMsg.append("第" + vo.getRowNum() + "行" + vo.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if ("库中该数据最多一条，请管理员清理数据库冗余数据！".equals(e.getMessage())) {
                return e.getMessage();
            } else {
                return "导入失败，请检查数据正确性";
            }
        }
    }

    private void saveExcel(List<FxCasualtyPercentVO> list) {
        for (int i = 0; i < list.size(); i++) {
            FxCasualtyPercentEntity entity = new FxCasualtyPercentEntity();
            FxCasualtyPercentVO vo = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(vo, entity);
            saveOrUpdate(entity);
        }
    }

    public void saveOrUpdate(FxCasualtyPercentEntity entity) {
        FxCasualtyPercentQueryParams queryParams = new FxCasualtyPercentQueryParams();
        queryParams.setProvince(entity.getProvince());
        queryParams.setCity(entity.getCity());
        queryParams.setArea(entity.getArea());
        queryParams.setIntensity(entity.getIntensity());
        queryParams.setDamageDegree(entity.getDamageDegree());

        List<FxCasualtyPercentEntity> entityList = fxCasualtyPercentNativeRepository.listFxCasualtyPercents(queryParams);
        // 若查到数据为空，则新增
        if (CollectionUtils.isEmpty(entityList)) {
            this.saveFxCasualtyPercent(entity);
        } else {
            if (entityList.size() == 1) {
                // 修改
                FxCasualtyPercentEntity sourceEntity = entityList.get(0);
                BeanUtil.copyPropertiesIgnoreNull(entity, sourceEntity);
                this.updateFxCasualtyPercent(sourceEntity);
            } else {
                throw new RuntimeException("库中该数据最多一条，请管理员清理数据库冗余数据！");
            }
        }
    }

    private void saveInitialize(FxCasualtyPercentEntity entity) {
        // 破坏程度
        List<DictItemEntity> damageDegrees = PlatformAPI.getDictAPI().getValidDictItemsByDictCode("damageDegree");
        for (int i = 0; i < damageDegrees.size(); i++) {
            String damageDegreeName = damageDegrees.get(i).getDictItemCode();
            entity.setDamageDegree(damageDegreeName);
            this.saveFxCasualtyPercent(entity);
        }
    }

}
